package com.easybuilder.blog.controller;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.easybuilder.common.utils.TimeUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.util.Date;


@Slf4j
@RestController
@RequestMapping("/file/upload")
public class UploadController {
    // 创建目录锁，防止重复创建同一个目录
    private static final Object DIR_LOCK = new Object();

    @Value("${file.uploadFolder:C://uploadFiles/}")
    private String uploadFolder;

    @PostMapping("/img")
    public Object uploadImg(MultipartFile[] files) {
        JSONObject result = new JSONObject();
        result.put("errno", "0");
        log.info("上传图片：{}", files);
        if (files != null && files.length > 0) {
            // 创建目录
            String date = TimeUtil.getTimeStr(new Date(), "yyyyMMdd");
            File dir = new File(uploadFolder + date);
            if (!dir.exists()) {
                synchronized (DIR_LOCK) {
                    if (!dir.exists()) {
                        dir.mkdir();
                    }
                }
            }
            JSONArray data = new JSONArray();
            for (MultipartFile file : files) {
                String originalFilename = file.getOriginalFilename();
                String[] arr = originalFilename.split("\\.");
                // 文件名
                String filename = arr[0];
                // 后缀名
                String suffix = arr[1];
                // 保存文件
                String parentPath = dir.getPath();
                try {
                    // 此处考虑用随机数给保存文件命名
                    String timeStr = TimeUtil.getTimeStr(new Date(), "HHmmss");
                    File saveFile = new File(parentPath + "/"  + timeStr + originalFilename);
                    file.transferTo(saveFile);
                    JSONObject item = new JSONObject();
                    String name = saveFile.getName();
                    item.put("url", "/file/"+dir.getName()+ "/" +name);
                    item.put("alt", "");
                    item.put("href", "");
                    data.add(item);
                } catch (IOException e) {
                    e.printStackTrace();
                }
                long size = file.getSize();
                log.info("文件名称：{}，文件大小：{}", originalFilename, size);
            }
            result.put("data", data);
        }

        return result.toJSONString();
    }

}


